package controllers;


import java.util.List;

import play.data.DynamicForm;
import play.data.Form;
import play.libs.Akka;
import play.libs.F.Callback;
import play.libs.F.Callback0;
import play.mvc.*;
import scala.concurrent.duration.Duration;
import akka.actor.ActorRef;
import akka.actor.Cancellable;
import akka.actor.Props;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import views.html.*;
import models.Constants;
import models.DB;
import models.Model;

public class Application extends Controller {
  
    /**
     * Display the home page.
     */
    public static Result index() {
        return ok(index.render());
    }
    
    public static Result main() {
    	return ok(views.html.home.render(null, null));
    }
    
    public static Result authenticate() {
    	DynamicForm boundForm = Form.form().bindFromRequest();
    	String username = boundForm.get("username");
    	//username = "admin";
		session().put("authentication", "true");
		session().put("username", username);
		session().put("previous_page", session().get("current_page"));
		session().put("current_page", "/home");
    	
    	for (String u : Constants.USERS) {
    		if (username.equals(u)) {
    			session().put("username", u);
    			//return ok("Success");
            	return ok(views.html.home.render("home", null));
    		}
    	}
    	return redirect("/");		
    }
    
    public static Result text() {
    	return ok(views.html.text.render());
    }

    @BodyParser.Of(play.mvc.BodyParser.AnyContent.class)
    public static Result open() {
    	List<String> files = DB.open();
    	JSONArray jArray = new JSONArray();
    	for (int i=0; i< files.size(); i++) {
    		JSONObject obj = new JSONObject();
    		try {
				obj.put(String.valueOf(i), files.get(i));
			} catch (JSONException e) {
				e.printStackTrace();
			}
    		jArray.put(obj);
    		System.out.println(files.get(i));
    	}
    	
    	return ok(jArray.toString());
    }
    public static Result load(String filename) {
    	String content = null;
    	content = DB.read(filename);
    	return ok(views.html.text.render());
    }
    
    public static Result save(String filename) {
    	System.out.println("Filename: " + filename);
    	DB.save(filename);
    	return ok(views.html.text.render());
    }
    
    public static Result textJs() {
        return ok(views.js.text.render());
    }

    public static WebSocket<String> textWs() {
        return new WebSocket<String>() {
            public void onReady(WebSocket.In<String> in, WebSocket.Out<String> out) {
                final ActorRef pingActor = Akka.system().actorOf(Props.create(Model.class, in, out));
                final Cancellable cancellable = 
                		Akka.system().scheduler().schedule(Duration.create(1, java.util.concurrent.TimeUnit.SECONDS),
                				Duration.create(Constants.UPDATE_RATE, java.util.concurrent.TimeUnit.SECONDS),
                				pingActor,
                				"Tick",
								Akka.system().dispatcher(),
								null);

                in.onMessage(new Callback<String>() {
                    public void invoke(String event) {
                      System.out.println("Got input event: " + event);  
                      // Flush text input into database
                      DB.setText(event);
                    } 
                 });
                
                
                in.onClose(new Callback0() {
                    @Override
                    public void invoke() throws Throwable {
                        cancellable.cancel();
                    }
                });
            }

        };
    }

    
    /**
     * Display the text editing panel.
     */
//    public static Result panel(String username) {
//        if(username == null || username.trim().equals("")) {
//            flash("error", "Please choose a valid username.");
//            return redirect(routes.Application.index());
//        }
//        return ok(panel.render(username));
//    }
//
//    /**
//     * Handle the write to document.
//     */
//    public static WebSocket<JsonNode> write(final String username) {
//        return new WebSocket<JsonNode>() {
//            
//            // Called when the Websocket Handshake is done.
//            public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out){
//                
//                // Join the chat room.
//                try { 
//                    Panel.join(username, in, out);
//                } catch (Exception ex) {
//                    ex.printStackTrace();
//                }
//            }
//        };
//    }
  
}
